package admin

import (
	"context"
	"errors"

	"server/internal/svc"
	"server/internal/types"
	"server/models"
	"server/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type RoleSaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRoleSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RoleSaveLogic {
	return &RoleSaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RoleSaveLogic) RoleSave(req *types.RoleSaveReq) (resp string, err error) {
	check := &models.AdminRole{}
	result := utils.GetData(check)
	if (req.Id == 0 && result) || (req.Id != check.ID && result) {
		return "", errors.New("角色名已经存在")
	}

	role := &models.AdminRole{
		Name:   req.Name,
		Desc:   req.Desc,
		Status: req.Status,
	}

	if req.Id == 0 {
		// 创建新角色
		err = utils.InsertData(role)
	} else {
		// 更新现有角色
		err = utils.UpdateById(req.Id, role)
	}

	if err != nil {
		logx.Errorf("操作角色失败: %v", err)
		return "", err
	}

	return "操作成功", nil
}
